package cn.itcast.homework.web;

import cn.itcast.homework.dto.PageResult;
import cn.itcast.homework.dto.SearchRequest;
import cn.itcast.homework.po.ItemPO;
import cn.itcast.homework.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity<ItemPO> queryItemById(@PathVariable("id") Long id) {
        ItemPO itemPO = itemService.queryById(id);
        if (itemPO == null) {
            // 查询失败，返回404
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        // 查询成功，返回200
        return ResponseEntity.status(HttpStatus.OK).body(itemPO);
    }

    /**
     * 新增商品
     *
     * @param itemPO
     * @return
     */
    @PostMapping
    public ResponseEntity<Long> saveItem(ItemPO itemPO) {
        try {
            // ...处理新增
            Long id = itemService.save(itemPO);
            // 新增成功，返回201
            return ResponseEntity.status(HttpStatus.CREATED).body(id);
        } catch (Exception e) {
            e.printStackTrace();
            // 新增失败，返回400
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

    /**
     * 搜索商品
     *
     * @param request 请求参数
     * @return 分页结果
     */
    @GetMapping("list")
    public ResponseEntity<PageResult> searchItem(SearchRequest request) {
        PageResult result = itemService.search(request);
        // 返回200，并携带数据
        return ResponseEntity.ok(result);
    }

}
